package com.pks.datacenter.listener;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import com.pks.datacenter.config.MyConfig;
import com.pks.datacenter.entity.basic.JobInfo;
import com.pks.datacenter.job.QuartzJob;
import com.pks.datacenter.service.basic.JobInfoService;
import com.pks.datacenter.utils.QuartzManager;

/**
 * 在springboot 项目启动后需要执行的内容
 * @author pks
 * @date 2020年7月30日
 */
@SuppressWarnings("unused")
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
    
	private final static Logger logger = LoggerFactory.getLogger(ApplicationRunnerImpl.class);
	@Autowired
	private JobInfoService jobInfoService;
	@Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("springboot 项目启动后需要执行的内容");
        try {
        	System.out.println();
        	List<JobInfo> list = jobInfoService.find(null, jobInfoService.initQbuilder("state", JobInfo.state_on), null);
    		for (JobInfo obj : list) {
    			try {
    				QuartzManager.addJob("job_"+obj.getId(), QuartzJob.class, obj.getExec_time(), obj.getId().toString());
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("任务：【" + obj.getName() +" 】启动失败 ：msg ：" + e.getMessage());
				}
    		}
        	genTemplateFile(MyConfig.getSavePath()  + File.separator + "exceltemplate" + File.separator + "blanktemplate.xls", "exceltemplate" +  File.separator + "blanktemplate.xls");
		} catch (Exception e) {
			e.printStackTrace();
		}
        
        
    	
    }
	
	
	/**
     * 将项目中的/resources/目录下的需要处理的模板文件生成到对应的磁盘目录中，作为业务处理
     * @param filePath 磁盘文件绝对路径
     * @param resourcesPath 模板文件相对于/resources的路径 如 “excelTemplate/template.xls”
     * @author pks
     * @date 2020年7月30日
     */
    public static void genTemplateFile(String filePath,String resourcesPath){
    	try {
    		logger.error("filePath:" + filePath);
    		logger.error("resourcesPath:" + resourcesPath);
			File file = new File(filePath);
			if(!file.exists()){
				ClassPathResource classPathResource = new ClassPathResource(resourcesPath);
				InputStream inputStream = classPathResource.getInputStream();
				logger.error("inputStream"+inputStream.toString());
				FileUtils.copyInputStreamToFile(inputStream, file);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
}
